package com.imooc.springcloud;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @desc
 * @author zkw
 * @date 2021-03-27
 */
@RestController
@Slf4j
public class Controller {

    @Autowired
    private MyService myService;

    @Autowired
    private RequestCacheService requestCacheService;

    @GetMapping("/fallback")
    public String fallback() {
        return myService.error();
    }

    @GetMapping("/timeout")
    public String timeout(Integer timeout) {
        return myService.retry(timeout);
    }

    /**
     * 超时配置
     * @param timeout
     * @return
     */
    @GetMapping("/timeout2")
    @HystrixCommand(fallbackMethod = "timeoutFallback",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
            })
    public String timeout2(Integer timeout) {
        return myService.retry(timeout);
    }

    public String timeoutFallback(Integer timeout) {
        return "timeout";
    }

    @GetMapping("cache")
    public Friend cache(String name) {
        //同一个上下文中只调用一次
        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        try {
            Friend friend = requestCacheService.requestCache(name);
            friend = requestCacheService.requestCache(name);
            return friend;
        } finally {
            context.close();
        }
    }

    /**
     * lombok注解：@Cleanup 关闭资源，默认调用对象的close()方法，（ @Cleanup("shutdown"): 可指定方法名）
     * @param name
     * @return
     */
    @GetMapping("cache2")
    public Friend cache2(String name) {
        //同一个上下文中只调用一次
        @Cleanup HystrixRequestContext context = HystrixRequestContext.initializeContext();
        Friend friend = requestCacheService.requestCache(name);
        name += "!";
        friend = requestCacheService.requestCache(name);
        return friend;
    }

}
